'use strict'

import { app, protocol, BrowserWindow } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'

const fs = require("fs");
const path = require("path")
const AdmZip = require('adm-zip');
const mammoth = require('mammoth');

const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
    { scheme: 'app', privileges: { secure: true, standard: true } }
])

let win = null;

async function createWindow() {
    // Create the browser window.
    win = new BrowserWindow({
        width: 1024,
        height: 768,
        webPreferences: {
            webSecurity: false, //取消跨域限制
            // Use pluginOptions.nodeIntegration, leave this alone
            // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
            // nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
            nodeIntegration: true
        }
    })

    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        if (!process.env.IS_TEST) win.webContents.openDevTools()
    } else {
        createProtocol('app')
            // Load the index.html when not in development
        win.loadURL('app://./index.html')
    }


    //通信模块，mian process与renderer process（web page）
    const { ipcMain } = require('electron') //监听web page里发出的message

    ipcMain.on('unzip', () => {
        console.log("******************* unzip ************************** ");
        //转换路径格式为绝对路径
        let inputPath = path.resolve("./downloads/");
        let files = fs.readdirSync(inputPath);
        files.forEach(file => {
            if (path.extname(file) == ".zip") {
                const filepath = path.join(inputPath, file)
                console.log(filepath)

                //中文乱码问题: https://www.cnblogs.com/wupeng88/p/10635709.html
                try {
                    const zippath = path.resolve("./unzip/")
                    const zip = new AdmZip(filepath);
                    zip.extractAllTo(zippath);
                } catch (e) {
                    console.log(e)
                }

            }
        });
        console.log("******************* unzip finished ************************** ");
        win.webContents.send('unzipstate', "unzip finished ")
    })

    ipcMain.on('search', (event, args) => {

        console.log("******************* search ************************** ")
        console.log(args);
        let inputPath = path.resolve("./unzip/");
        let files = fs.readdirSync(inputPath);

        let resulPath = path.resolve("./result/");
        fs.exists(resulPath, (exists) => {
            if (!exists) {
                console.log("文件不存在");
                fs.mkdir("./result", (err) => {
                    console.log("创建成功");
                })
            } else {
                console.log("文件存在");
            }
        });
        let index = 0;
        files.forEach(file => {
            if (path.extname(file) == ".docx") {

                const filepath = path.join(inputPath, file)
                const targetPath = path.join(resulPath, file);
                // console.log(filepath)
                mammoth.extractRawText({ path: filepath })
                    .then(function(result) {
                        let text = result.value; // The raw text 
                        // if (text.match("2020年12月23日9:30时")) {
                        if (text.match(args)) {
                            console.log(filepath);
                            log_on_ui_pipe(`find: ${filepath}`)
                            fs.readFile(filepath, function(err, data) {
                                if (err) throw new Error('something wrong was happended');
                                fs.writeFile(targetPath, data, function(err) {
                                    if (err) throw new Error('something wrong was happended');
                                })
                            })
                        }

                        log_on_ui_pipe(`searching: ${index++}`)
                            // console.log(text);
                            // var messages = result.messages;
                            // console.log(result);
                    }).catch(function(err) {
                        // console.log(err);
                    })
            }
        });

        log_on_ui_pipe(`finish !!!`)
    })

    ipcMain.on('clear', (event, args) => {

        console.log("******************* clear ************************** ")
        let inputPath = path.resolve("./downloads/");
        deletefile(inputPath);
        inputPath = path.resolve("./unzip/");
        deletefile(inputPath);
        inputPath = path.resolve("./result/");
        deletefile(inputPath);
    })

    ipcMain.on('download', (event, args) => {
        console.log(args);
        //下面这句会触发will-download事件
        win.webContents.downloadURL(args);
    })

    win.webContents.session.on('will-download', (event, item, webContents) => {

        //设置文件存放位置，如果用户没有设置保存路径，Electron将使用默认方式来确定保存路径（通常会提示保存对话框）
        let savepath = path.resolve("./downloads/");
        item.setSavePath(savepath + "/" + `${new Date().getTime()}` + item.getFilename())
        item.on('updated', (event, state) => {
            // console.log('updated')
            if (state === 'interrupted') {
                console.log('Download is interrupted but can be resumed')
                win.webContents.send('downstate', state)
            } else if (state === 'progressing') {
                if (item.isPaused()) {
                    console.log('Download is paused')
                } else {
                    console.log(`Received bytes: ${item.getReceivedBytes()}`)
                    win.webContents.send('log', `Received bytes: ${item.getReceivedBytes()}`)
                }
            }
        })
        item.once('done', (event, state) => {
            // console.log('done')
            if (state === 'completed') {
                console.log('Download successfully')
                    //回显 调用渲染进程方法
                win.webContents.send('downstate', state)
            } else {
                console.log(`Download failed: ${state}`)
                    //回显 调用渲染进程方法
                win.webContents.send('downstate', state)
            }
        })
    })
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async() => {
    if (isDevelopment && !process.env.IS_TEST) {
        // Install Vue Devtools
        try {
            await installExtension(VUEJS_DEVTOOLS)
        } catch (e) {
            console.error('Vue Devtools failed to install:', e.toString())
        }
    }
    createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}

function log_on_ui_pipe(msg) {
    win.webContents.send('log', msg);
}

function deletefile(path) {
    console.log(path);
    if (fs.existsSync(path)) {
        let files = fs.readdirSync(path);

        console.log(files);

        files.forEach(function(file, index) {
            var curPath = path + "/" + file;

            console.log(curPath);

            if (fs.statSync(curPath).isDirectory()) { // recurse

                deleteFolderRecursive(curPath);

            } else { // delete file

                fs.unlinkSync(curPath);
                log_on_ui_pipe(`delete ${curPath}`)

            }

        });

        //fs.rmdirSync(path);
    }
}